<template>
  <view class="update-settings">
    <view class="settings-section">
      <view class="section-title">自动更新</view>
      
      <!-- 自动检查更新 -->
      <view class="setting-item">
        <view class="setting-info">
          <text class="setting-name">自动检查更新</text>
          <text class="setting-desc">定期检查应用更新</text>
        </view>
        <switch :checked="settings.enabled" @change="handleToggle('enabled', $event)" />
      </view>
      
      <!-- 仅WiFi下载 -->
      <view class="setting-item" :class="{ disabled: !settings.enabled }">
        <view class="setting-info">
          <text class="setting-name">仅WiFi下载</text>
          <text class="setting-desc">仅在WiFi网络下下载更新</text>
        </view>
        <switch 
          :checked="settings.wifiOnly"
          :disabled="!settings.enabled"
          @change="handleToggle('wifiOnly', $event)" 
        />
      </view>
      
      <!-- 检查频率 -->
      <view class="setting-item clickable" :class="{ disabled: !settings.enabled }" @click="selectCheckInterval">
        <view class="setting-info">
          <text class="setting-name">检查频率</text>
          <text class="setting-desc">{{ getIntervalText(settings.checkInterval) }}</text>
        </view>
        <text class="setting-arrow">></text>
      </view>
    </view>
    
    <view class="settings-section">
      <view class="section-title">版本信息</view>
      
      <!-- 当前版本 -->
      <view class="setting-item">
        <view class="setting-info">
          <text class="setting-name">当前版本</text>
          <text class="setting-desc">v{{ currentVersion }}</text>
        </view>
      </view>
      
      <!-- 最后检查时间 -->
      <view class="setting-item">
        <view class="setting-info">
          <text class="setting-name">最后检查</text>
          <text class="setting-desc">{{ lastCheckTime }}</text>
        </view>
      </view>
      
      <!-- 手动检查更新 -->
      <view class="setting-item clickable" @click="checkForUpdate">
        <view class="setting-info">
          <text class="setting-name">检查更新</text>
          <text class="setting-desc">立即检查是否有新版本</text>
        </view>
        <text class="setting-arrow">></text>
      </view>
    </view>
    
    <view class="settings-section">
      <view class="section-title">更新历史</view>
      
      <!-- 更新日志 -->
      <view class="setting-item clickable" @click="viewUpdateLogs">
        <view class="setting-info">
          <text class="setting-name">更新日志</text>
          <text class="setting-desc">查看更新历史记录 ({{ logCount }}条)</text>
        </view>
        <text class="setting-arrow">></text>
      </view>
      
      <!-- 清除日志 -->
      <view class="setting-item clickable" @click="clearUpdateLogs">
        <view class="setting-info">
          <text class="setting-name">清除日志</text>
          <text class="setting-desc">删除所有更新历史记录</text>
        </view>
        <text class="setting-arrow">></text>
      </view>
    </view>
    
    <!-- 更新日志弹窗 -->
    <view v-if="showLogsModal" class="modal-overlay" @click="closeLogsModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">更新日志</text>
          <text class="modal-close" @click="closeLogsModal">✕</text>
        </view>
        <view class="modal-body">
          <view v-if="logs.length === 0" class="empty-logs">
            <text class="empty-text">暂无更新日志</text>
          </view>
          <view v-else class="logs-list">
            <view v-for="(log, index) in logs" :key="index" class="log-item">
              <view class="log-header">
                <text class="log-action">{{ getActionText(log.action) }}</text>
                <text class="log-time">{{ formatTime(log.timestamp) }}</text>
              </view>
              <view v-if="log.version" class="log-detail">
                <text class="log-version">版本: {{ log.version }}</text>
              </view>
              <view v-if="log.error" class="log-error">
                <text class="error-text">{{ log.error }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import autoUpdateChecker from '@/utils/update/auto-checker.js'
import wgtHotUpdate from '@/utils/wgt-hot-update.js'
import settingsStorage from '@/utils/settings/storage.js'

export default {
  name: 'UpdateSettings',
  data() {
    return {
      settings: {
        enabled: true,
        wifiOnly: false,
        checkInterval: 24 * 60 * 60 * 1000
      },
      currentVersion: '1.0.0',
      lastCheckTime: '从未检查',
      logCount: 0,
      logs: [],
      showLogsModal: false
    }
  },
  async onLoad() {
    this.loadSettings()
    await this.loadVersion()
    this.loadLastCheckTime()
    this.loadLogs()
  },
  
  async onShow() {
    // 页面显示时刷新数据（可能从其他页面返回）
    await this.loadVersion()
    this.loadLastCheckTime()
    this.loadLogs()
  },
  
  methods: {
    loadSettings() {
      // 从autoUpdateChecker读取当前配置
      this.settings = {
        enabled: autoUpdateChecker.config.enabled,
        wifiOnly: autoUpdateChecker.config.wifiOnly,
        checkInterval: autoUpdateChecker.config.checkInterval
      }
      console.log('[UpdateSettings] 加载设置:', this.settings)
    },
    
    async loadVersion() {
      try {
        // 确保版本已初始化（如果本地存储没有，则从系统获取）
        await wgtHotUpdate.init()
        
        // 获取当前版本（从本地存储读取，已由init()初始化）
        this.currentVersion = wgtHotUpdate.getCurrentVersion()
        console.log('[UpdateSettings] 当前版本:', this.currentVersion)
      } catch (error) {
        console.error('[UpdateSettings] 加载版本失败:', error)
        // 如果获取失败，尝试从本地存储读取
        const savedVersion = uni.getStorageSync('app_version')
        if (savedVersion) {
          this.currentVersion = savedVersion
        } else {
          this.currentVersion = '1.0.0'
        }
      }
    },
    
    loadLastCheckTime() {
      const lastCheck = autoUpdateChecker.getLastCheckTime()
      if (lastCheck) {
        this.lastCheckTime = this.formatTime(lastCheck)
      }
    },
    
    loadLogs() {
      this.logs = autoUpdateChecker.getUpdateLogs()
      this.logCount = this.logs.length
    },
    
    handleToggle(key, event) {
      const value = event.detail.value
      console.log(`[UpdateSettings] 切换设置: ${key} = ${value}`)
      
      this.settings[key] = value
      
      // 更新autoUpdateChecker配置
      autoUpdateChecker.config[key] = value
      
      // 保存到本地存储
      settingsStorage.save('update', this.settings)
      
      uni.showToast({
        title: '设置已保存',
        icon: 'success',
        duration: 1500
      })
      
      this.$emit('settings-changed', this.settings)
    },
    
    selectCheckInterval() {
      if (!this.settings.enabled) return
      
      uni.showActionSheet({
        itemList: ['每天检查', '每周检查', '每月检查'],
        success: (res) => {
          const intervals = [
            24 * 60 * 60 * 1000,      // 每天
            7 * 24 * 60 * 60 * 1000,  // 每周
            30 * 24 * 60 * 60 * 1000  // 每月
          ]
          
          this.settings.checkInterval = intervals[res.tapIndex]
          autoUpdateChecker.config.checkInterval = this.settings.checkInterval
          settingsStorage.save('update', this.settings)
          
          uni.showToast({
            title: '检查频率已设置',
            icon: 'success',
            duration: 1500
          })
        }
      })
    },
    
    getIntervalText(interval) {
      const day = 24 * 60 * 60 * 1000
      if (interval === day) return '每天检查'
      if (interval === 7 * day) return '每周检查'
      if (interval === 30 * day) return '每月检查'
      return '自定义'
    },
    
    async checkForUpdate() {
      try {
        uni.showLoading({
          title: '检查更新中...',
          mask: true
        })
        
        // 配置Gitee信息
        wgtHotUpdate.setGiteeConfig('xuxinzhi2206', 'moe_web', '')
        
        const result = await wgtHotUpdate.checkForUpdate()
        
        uni.hideLoading()
        
        // 记录检查时间（使用 autoUpdateChecker 的方法）
        autoUpdateChecker.recordCheckTime()
        
        // 记录更新日志
        autoUpdateChecker.logUpdateAction('check', {
          hasUpdate: result.hasUpdate,
          currentVersion: result.currentVersion,
          remoteVersion: result.remoteVersion,
          message: result.message
        })
        
        // 更新最后检查时间显示
        this.loadLastCheckTime()
        
        // 更新当前版本显示（可能检查后版本有变化）
        this.loadVersion()
        
        // 更新日志数量
        this.loadLogs()
        
        if (result.hasUpdate) {
          uni.showModal({
            title: '发现新版本',
            content: `当前版本: v${result.currentVersion}\n最新版本: v${result.remoteVersion}\n\n${result.message}`,
            confirmText: '立即更新',
            cancelText: '稍后再说',
            success: (res) => {
              if (res.confirm) {
                // 记录升级日志
                autoUpdateChecker.logUpdateAction('upgrade', {
                  fromVersion: result.currentVersion,
                  toVersion: result.remoteVersion
                })
                // 触发更新
                this.$emit('start-update', result)
              } else {
                // 记录忽略日志
                autoUpdateChecker.logUpdateAction('ignore', {
                  version: result.remoteVersion
                })
              }
            }
          })
        } else {
          uni.showModal({
            title: '已是最新版本',
            content: `当前版本: v${result.currentVersion}\n\n${result.message}`,
            showCancel: false
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('[UpdateSettings] 检查更新失败:', error)
        
        // 记录失败日志
        autoUpdateChecker.logUpdateAction('check', {
          hasUpdate: false,
          error: error.message || '检查更新失败'
        })
        
        // 更新日志数量
        this.loadLogs()
        
        uni.showModal({
          title: '检查失败',
          content: error.message || '网络连接异常，请稍后重试',
          showCancel: false
        })
      }
    },
    
    viewUpdateLogs() {
      this.loadLogs()
      this.showLogsModal = true
    },
    
    closeLogsModal() {
      this.showLogsModal = false
    },
    
    clearUpdateLogs() {
      uni.showModal({
        title: '清除日志',
        content: '确定要删除所有更新历史记录吗？',
        success: (res) => {
          if (res.confirm) {
            autoUpdateChecker.clearUpdateLogs()
            this.loadLogs()
            uni.showToast({
              title: '日志已清除',
              icon: 'success',
              duration: 1500
            })
          }
        }
      })
    },
    
    getActionText(action) {
      const actionMap = {
        'check': '检查更新',
        'upgrade': '开始升级',
        'upgrade_failed': '升级失败',
        'ignore': '忽略更新',
        'close': '关闭提示'
      }
      return actionMap[action] || action
    },
    
    formatTime(timestamp) {
      try {
        const date = new Date(timestamp)
        const now = new Date()
        const diff = now - date
        
        // 小于1分钟
        if (diff < 60 * 1000) {
          return '刚刚'
        }
        
        // 小于1小时
        if (diff < 60 * 60 * 1000) {
          return `${Math.floor(diff / 60 / 1000)}分钟前`
        }
        
        // 小于1天
        if (diff < 24 * 60 * 60 * 1000) {
          return `${Math.floor(diff / 60 / 60 / 1000)}小时前`
        }
        
        // 小于7天
        if (diff < 7 * 24 * 60 * 60 * 1000) {
          return `${Math.floor(diff / 24 / 60 / 60 / 1000)}天前`
        }
        
        // 格式化日期
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hour = String(date.getHours()).padStart(2, '0')
        const minute = String(date.getMinutes()).padStart(2, '0')
        
        return `${year}-${month}-${day} ${hour}:${minute}`
      } catch (error) {
        return '未知时间'
      }
    }
  }
}
</script>

<style scoped>
.update-settings {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20rpx;
}

.settings-section {
  background: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.section-title {
  padding: 24rpx 30rpx 16rpx;
  font-size: 28rpx;
  font-weight: bold;
  color: #2d3436;
  background: #f8f9fa;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: opacity 0.3s ease;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-item.disabled {
  opacity: 0.5;
}

.setting-item.clickable {
  cursor: pointer;
}

.setting-item.clickable:active {
  background: #f8f9fa;
}

.setting-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.setting-name {
  font-size: 28rpx;
  color: #2d3436;
  font-weight: 500;
}

.setting-desc {
  font-size: 24rpx;
  color: #636e72;
}

.setting-arrow {
  font-size: 20rpx;
  color: #b2bec3;
  margin-left: 12rpx;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  padding: 40rpx;
}

.modal-content {
  background: white;
  border-radius: 20rpx;
  width: 100%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
}

.modal-close {
  font-size: 28rpx;
  cursor: pointer;
  padding: 8rpx;
}

.modal-body {
  max-height: 60vh;
  overflow-y: auto;
}

.empty-logs {
  padding: 80rpx 40rpx;
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #b2bec3;
}

.logs-list {
  padding: 20rpx;
}

.log-item {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
}

.log-item:last-child {
  margin-bottom: 0;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.log-action {
  font-size: 26rpx;
  font-weight: bold;
  color: #2d3436;
}

.log-time {
  font-size: 22rpx;
  color: #b2bec3;
}

.log-detail {
  margin-bottom: 8rpx;
}

.log-version {
  font-size: 24rpx;
  color: #636e72;
}

.log-error {
  margin-top: 8rpx;
  padding: 12rpx;
  background: #fff5f5;
  border-radius: 8rpx;
}

.error-text {
  font-size: 22rpx;
  color: #e74c3c;
}
</style>
